import { reqAddOrUpdateShopCart, 
    reqShopCartList,
     reqUpdateOneIsChecked, 
     reqUpdateAllIsChecked ,
     reqDeleteShopCart,
     reqDeleteAllShopCart} from '@/api'

const state = {
shopCartList: []
}
const mutations = {
GETSHOPCARTLIST(state, val) {
    state.shopCartList = val
}
}

const actions = {

// 判断是否将购物车信息提交到了数据库(还可以修改数量)
async addOrUpdateShopCart({ commit }, { skuId, skuNum }) {
    const result = await reqAddOrUpdateShopCart(skuId, skuNum)
    if (result.code === 200) {
        return 'ok'
    } else {
        return Promise.reject(new Error('添加失败'))
    }
},

// 获取新的购物车列表数据
async getShopCartList({ commit }) {
    const result = await reqShopCartList();
    if (result.code == 200) {
        commit('GETSHOPCARTLIST', result.data)
    }
},

//请求修改单的选中状态
async updateOneIsChecked({ commit }, { skuId, isChecked }) {
    const result = await reqUpdateOneIsChecked(skuId, isChecked)
    if (result.code === 200) {
        return 'ok'
    } else {
        return Promise.reject(new Error('修改失败'))
    }
},
//请求修全部的选中状态
async updateAllIsChecked({ commit }, { isChecked, skuIds }) {
    const result = await reqUpdateAllIsChecked(isChecked, skuIds)
    if (result.code === 200) {
        return 'ok'
    } else {
        return Promise.reject(new Error('修改失败'))
    }
},
// 请求删除单个的购物车
async deleteOneShopCart({ commit }, skuId) {
    const result = await reqDeleteShopCart(skuId)
    if (result.code === 200) {
        return 'ok'
    } else {
        return Promise.reject(new Error('failed'))
    }
},

//请求删除多个购物车
async deleteAllShopCart({ commit }, skuIds) {
    const result = await reqDeleteAllShopCart(skuIds)
    if (result.code === 200) {
        return 'ok'
    } else {
        return Promise.reject(new Error('failed'))
    }
},

}
const getters = {
    shopCartList(state){
         return state.shopCartList[0].cartInfoList || []
    }
}

export default {
state,
mutations,
actions,
getters
}